﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace com.iot.core.util
{
    public class DataTableUtil
    {
        public static List<T> ToList<T>(  DataTable dt) where T : new()
        {
            List<T> ts = new List<T>();
            var tp = typeof(T);
            PropertyInfo[] properties = tp.GetProperties(BindingFlags.Instance | BindingFlags.Public);

            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();
                foreach(var p in properties)
                {
                    if (!dt.Columns.Contains(p.Name))
                    {
                        continue;
                    }
                    object value = dr[p.Name];
                    p.SetValue(t, ConvertHelper.ChangeType(value, p.PropertyType), null);
                } 
                ts.Add(t);
            }
            return ts;
        } 
    }
}
